from typing import Dict

from kubernetes import client

from k8s.base import KubernetesAPI


class CoreAPI(KubernetesAPI):

    def _make_api(self, api_client):
        self.Api = client.CoreV1Api(api_client)

    def get_nodes(self, node_name: str = None) -> Dict[str, client.V1Node]:
        # todo 加入label filter
        kwargs = {}
        if node_name:
            kwargs["field_selector"] = "metadata.name={}".format(node_name)

        r: client.V1NodeList = self.Api.list_node(**kwargs)
        result = {}
        for node in r.items:
            addresses = node.status.addresses
            node_ip = ""
            for addr in addresses:
                if addr.type == "InternalIP":
                    node_ip = addr.address
                    break
            result[node_ip] = node
        return result

    def label_node(self, node: str, key: str, value: str):
        try:
            r = self.Api.patch_node(
                **{
                    "name": node,
                    "body": {
                        "metadata": {
                            "labels": {
                                key: value
                            }
                        }
                    }
                }
            )
            return r, None
        except Exception as e:
            return None, str(e)

    def taint_node(self, node: str, effect: str, key: str):
        try:
            r = self.Api.patch_node(
                **{
                    "name": node,
                    "body": {
                        "spec": {
                            "taints": [{
                                "effect": effect,
                                "key": key,
                            }]
                        }
                    }
                }
            )
            return r, None
        except Exception as e:
            return None, str(e)

    def get_pods(self, ns, pod_name: str = None) -> Dict[str, client.V1Pod]:
        kwargs = {}
        if pod_name:
            kwargs["field_selector"] = "metadata.name={}".format(pod_name)
        r: client.V1PodList = self.Api.list_namespaced_pod(ns)
        result = {}
        for pod in r.items:
            result[pod.metadata.name] = pod

        return result

    def delete_pod(self, ns, pod_name: str):
        r: client.V1Pod = self.Api.delete_namespaced_pod(pod_name, ns)

        return r

    def evict_pod(self, ns, namespace):
        pass
